// 1. React核心库
import React, { useEffect, useState } from 'react';

// 2. UI组件库 - 按字母顺序
import { Card, Checkbox, Space, Button, message, Spin, Tag, Alert } from 'antd';

// 3. 图标库
import { SafetyOutlined, ArrowLeftOutlined, SaveOutlined, ReloadOutlined, UserOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 路由相关
import { useParams, history } from '@umijs/max';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import { usePermissionStore } from '@/stores/permissionStore';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { PermissionExtension, User, UserPermissionExtension } from '@/services/generated';

interface ModulePermissions {
  module: string;
  moduleName: string;
  permissions: UserPermissionExtension[];
  count: number;
}

const UserPermissions: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [user, setUser] = useState<User | null>(null);
  const [modulePermissions, setModulePermissions] = useState<ModulePermissions[]>([]);
  const [selectedPermissions, setSelectedPermissions] = useState<Set<number>>(new Set());

  // 模块名称映射
  const moduleNameMap: Record<string, string> = {
    'admin': '管理后台',
    'auth': '认证系统', 
    'authentication': '用户管理',
    'contenttypes': '内容类型',
    'permissions': '权限管理',
    'sessions': '会话管理',
  };

  // 获取用户信息
  const fetchUser = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.users.usersRetrieve({ id: parseInt(id!) });
      setUser(response.data);
    } catch (error) {
      message.error('获取用户信息失败');
    }
  };

  // 获取所有权限
  const fetchPermissions = async () => {
    try {
      setLoading(true);
      await autoLoginInDev();
      
      const response = await apiClients.users.usersAllPermissionsRetrieve();

      const permissions = response?.data || [];
      
      // 按模块分组
      const groupedByModule: Record<string, UserPermissionExtension[]> = {};
      permissions.forEach(permission => {
        const module = permission.module || 'unknown';
        if (!groupedByModule[module]) {
          groupedByModule[module] = [];
        }
        groupedByModule[module].push(permission);
      });

      // 转换为数组格式
      const moduleData: ModulePermissions[] = Object.entries(groupedByModule).map(([module, perms]) => ({
        module,
        moduleName: moduleNameMap[module] || module,
        permissions: perms,
        count: perms.length,
      }));

      // 按权限数量排序
      moduleData.sort((a, b) => b.count - a.count);
      
      setModulePermissions(moduleData);
    } catch (error) {
      message.error('获取权限数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取用户当前权限
  const fetchUserPermissions = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.users.usersUserPermissionsRetrieve({ id: parseInt(id!) });
      const userPermissions = response.data || [];

      // 将权限扩展ID添加到选中集合
      const userPerms = new Set<number>();
      userPermissions.forEach((perm: any) => {
        // 使用权限扩展的ID，而不是Django权限ID
        userPerms.add(perm.id);
      });

      setSelectedPermissions(userPerms);
    } catch (error) {
      message.error('获取用户权限失败');
    }
  };

  useEffect(() => {
    if (id) {
      fetchUser();
      fetchPermissions();
      fetchUserPermissions();
    }
  }, [id]);

  // 检查模块是否全选
  const isModuleAllSelected = (permissions: UserPermissionExtension[]): boolean => {
    return permissions.every(permission => selectedPermissions.has(permission.id!));
  };

  // 检查模块是否部分选中
  const isModuleIndeterminate = (permissions: UserPermissionExtension[]): boolean => {
    const selectedCount = permissions.filter(permission => selectedPermissions.has(permission.id!)).length;
    return selectedCount > 0 && selectedCount < permissions.length;
  };

  // 处理权限选择
  const handlePermissionChange = (permissionId: number, checked: boolean) => {
    const newSelected = new Set(selectedPermissions);
    if (checked) {
      newSelected.add(permissionId);
    } else {
      newSelected.delete(permissionId);
    }
    setSelectedPermissions(newSelected);
  };

  // 处理模块全选/取消全选
  const handleModuleChange = (modulePermissions: UserPermissionExtension[], checked: boolean) => {
    const newSelected = new Set(selectedPermissions);
    modulePermissions.forEach(permission => {
      if (checked) {
        newSelected.add(permission.id!);
      } else {
        newSelected.delete(permission.id!);
      }
    });
    setSelectedPermissions(newSelected);
  };

  // 保存权限分配
  const handleSave = async () => {
    try {
      setSaving(true);
      await autoLoginInDev();

      const permissionIds = Array.from(selectedPermissions);
      await apiClients.users.usersSetPermissionsCreate({
        id: parseInt(id!),
        userSetPermissionsRequest: {
          permission_extension_ids: permissionIds
        }
      });

      message.success(`权限分配保存成功，共分配${permissionIds.length}个权限`);

      // 强制刷新权限缓存
      const permissionStore = usePermissionStore.getState();
      await permissionStore.refreshPermissions();

      message.info('权限缓存已刷新');

    } catch (error) {
      message.error('保存权限分配失败');
    } finally {
      setSaving(false);
    }
  };

  return (
    <PageContainer
      title={
        <Space>
          <UserOutlined />
          为用户分配权限
          {user && <Tag color="blue">{user.username}</Tag>}
        </Space>
      }
      extra={[
        <Button key="back" icon={<ArrowLeftOutlined />} onClick={() => history.back()}>
          返回
        </Button>,
        <Button key="refresh" icon={<ReloadOutlined />} onClick={() => {
          fetchPermissions();
          fetchUserPermissions();
        }}>
          刷新
        </Button>,
        <Button 
          key="save" 
          type="primary" 
          icon={<SaveOutlined />} 
          loading={saving}
          onClick={handleSave}
        >
          保存权限分配
        </Button>,
      ]}
    >
      <Spin spinning={loading}>
        <Alert
          message="权限分配说明"
          description="您可以为用户分配具体的权限。勾选模块名称可以快速选择该模块下的所有权限，也可以展开模块选择具体的权限项。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        <div style={{ marginBottom: 16 }}>
          <Card size="small">
            <Space size="large">
              <span>总模块数: <strong>{modulePermissions.length}</strong></span>
              <span>总权限数: <strong>{modulePermissions.reduce((sum, m) => sum + m.count, 0)}</strong></span>
              <span>已选权限数: <strong style={{ color: '#1890ff' }}>{selectedPermissions.size}</strong></span>
            </Space>
          </Card>
        </div>

        {/* 权限分配区域 - 全部展开，横向排列 */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
          {modulePermissions.map(moduleData => (
            <Card key={moduleData.module} size="small">
              {/* 模块标题和全选 */}
              <div style={{ marginBottom: '16px', borderBottom: '1px solid #f0f0f0', paddingBottom: '12px' }}>
                <Space>
                  <Checkbox
                    checked={isModuleAllSelected(moduleData.permissions)}
                    indeterminate={isModuleIndeterminate(moduleData.permissions)}
                    onChange={(e) => handleModuleChange(moduleData.permissions, e.target.checked)}
                  >
                    <SafetyOutlined />
                    <strong style={{ fontSize: '16px' }}>{moduleData.moduleName}</strong>
                  </Checkbox>
                  <Tag color="blue">{moduleData.count} 个权限</Tag>
                  <Tag color="orange">
                    {moduleData.permissions.filter(p => selectedPermissions.has(p.id!)).length} 个已选择
                  </Tag>
                  <code style={{ color: '#666' }}>{moduleData.module}</code>
                </Space>
              </div>

              {/* 权限盒子 - 横向排列 */}
              <div style={{
                display: 'flex',
                flexWrap: 'wrap',
                gap: '12px'
              }}>
                {moduleData.permissions.map(permission => (
                  <div
                    key={permission.id}
                    style={{
                      padding: '12px 16px',
                      border: selectedPermissions.has(permission.id!) ? '2px solid #52c41a' : '1px solid #d9d9d9',
                      borderRadius: '8px',
                      backgroundColor: selectedPermissions.has(permission.id!) ? '#f6ffed' : '#fafafa',
                      cursor: 'pointer',
                      transition: 'all 0.3s ease',
                      minWidth: '180px',
                      maxWidth: '280px',
                      boxShadow: selectedPermissions.has(permission.id!) ? '0 2px 8px rgba(82, 196, 26, 0.2)' : '0 1px 4px rgba(0,0,0,0.1)'
                    }}
                    onClick={() => handlePermissionChange(permission.id!, !selectedPermissions.has(permission.id!))}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
                      e.currentTarget.style.transform = 'translateY(-2px)';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.boxShadow = selectedPermissions.has(permission.id!) ? '0 2px 8px rgba(82, 196, 26, 0.2)' : '0 1px 4px rgba(0,0,0,0.1)';
                      e.currentTarget.style.transform = 'translateY(0)';
                    }}
                  >
                    <Checkbox
                      checked={selectedPermissions.has(permission.id!)}
                      onChange={(e) => {
                        e.stopPropagation();
                        handlePermissionChange(permission.id!, e.target.checked);
                      }}
                    >
                      <span style={{
                        fontWeight: selectedPermissions.has(permission.id!) ? 'bold' : 'normal',
                        color: selectedPermissions.has(permission.id!) ? '#52c41a' : '#333',
                        fontSize: '14px'
                      }}>
                        {permission.permission_name}
                      </span>
                    </Checkbox>
                  </div>
                ))}
              </div>
            </Card>
          ))}
        </div>

        {modulePermissions.length === 0 && !loading && (
          <Card>
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <SafetyOutlined style={{ fontSize: 48, color: '#ccc', marginBottom: 16 }} />
              <p style={{ color: '#999' }}>暂无权限数据</p>
            </div>
          </Card>
        )}
      </Spin>
    </PageContainer>
  );
};

export default UserPermissions;
